package org.millioncall.yueyoga.admin.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.millioncall.openplatform.common.PaginateParams;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.common.StartLimitPairImpl;
import org.millioncall.openplatform.dao.PreparedQuery;
import org.millioncall.yueyoga.admin.dao.BaseDao;
import org.millioncall.yueyoga.admin.dao.StatusDAO;
import org.millioncall.yueyoga.admin.dao.TaskDAO;
import org.millioncall.yueyoga.admin.dao.UserDAO;
import org.millioncall.yueyoga.admin.model.AviatorExpression;
import org.millioncall.yueyoga.admin.model.HomePageTaskRecord;
import org.millioncall.yueyoga.admin.model.Member;
import org.millioncall.yueyoga.admin.model.Status;
import org.millioncall.yueyoga.admin.model.Task;
import org.millioncall.yueyoga.admin.service.advancedsearch.AviatorResultHandler;
import org.springframework.stereotype.Repository;

@Repository
public class TaskDAOImpl extends BaseDao implements TaskDAO {
	private static final String SAVE_TASK = "saveTask";
	private static final String UPDATE_TASK_BY_ID = "updateTaskById";
	private static final String DELETE_TASK_BY_ID = "deleteTaskById";
	private static final String FIND_TASK_BY_ID = "findTaskById";
	private static final String FIND_TASKS_BY_CONDITIONS = "findTasksByConditions";
	private static final String FIND_TASKRELATEDINFO_BY_ID = "findTaskRelatedInfoById";

	private StatusDAO statusDAO;

	private UserDAO userDAO;

	public List<Task> findTaskLimit() {
		return this.getPagableSqlSessionTemplate()
				.selectList("selectTaskLimit");
	}

	@Override
	public int save(Map<String, Object> map) {
		return this.save(SAVE_TASK, map);
	}

	@Override
	public int update(Map<String, Object> map) {
		return this.update(UPDATE_TASK_BY_ID, map);
	}

	@Override
	public int deleteById(Integer taskId) {
		return this.deleteById(DELETE_TASK_BY_ID, taskId);
	}

	@Override
	public int deleteByIds(String[] ids) {
		int len = 0;
		for (int i = 0; i < ids.length; i++) {
			String taskId = ids[i];
			if (StringUtils.isNotBlank(taskId)) {
				len += this.deleteById(Integer.valueOf(taskId));
			}
		}
		return len;
	}

	@Override
	public Task findTaskById(Map<String, Object> map) {
		if (map.get("taskId") == null) {
			List<Task> tasks = this.getPagableSqlSessionTemplate().selectList(
					FIND_TASK_BY_ID);
			return tasks != null ? tasks.get(0) : null;
		}
		return this.getPagableSqlSessionTemplate().selectOne(FIND_TASK_BY_ID,
				map);
	}

	/****
	 * 分页条件查询任务
	 */
	@Override
	public PaginatedList<Task> findTasksInPage(Map<String, Object> map,
			int start, int limit) {
		PreparedQuery<Task> pq = this.getPagableSqlSessionTemplate().findAll(
				FIND_TASKS_BY_CONDITIONS, map);
		PaginatedList<Task> pl = pq.list(new PaginateParams(
				new StartLimitPairImpl(start, limit)));

		if (pl != null && pl.size() > 0) {
			for (int i = 0; i < pl.size(); i++) {
				Task task = pl.get(i);
				if (task.getSubStatusId() != null) {
					task.setChildStatus(statusDAO.findById(task
							.getSubStatusId()));
				}
				Member member = task.getMember();
				if (member != null
						&& (StringUtils.isNotBlank(member.getSubstatus()))) {
					Status status = statusDAO.findByCode(member.getSubstatus());
					if (status != null) {
						task.getMember().setChildStatus(status);
						String parCode = status.getParentcode();
						// 根据父状态code,查询父状态
						if (StringUtils.isNotBlank(parCode)) {
							Status parStatus = statusDAO.findByCode(parCode);
							task.getMember().setParStatusName(
									parStatus == null ? "" : parStatus
											.getName());
						}
					}
				}
			}
		}
		return pl.size() > 0 ? pl : null;
	}

	@Override
	public Task findTaskRelatedInfoById(Map<String, Object> map) {
		return this.getPagableSqlSessionTemplate().selectOne(
				FIND_TASKRELATEDINFO_BY_ID, map);
	}

	@Override
	public PaginatedList<HomePageTaskRecord> findHomeTasksInPage(
			Map<String, Object> map, int start, int limit) {
		PreparedQuery<HomePageTaskRecord> pq = this
				.getPagableSqlSessionTemplate().findAll(
						"findTaskListForHomePage", map);
		PaginatedList<HomePageTaskRecord> pl = pq.list(new PaginateParams(
				new StartLimitPairImpl(start, limit)));
		return pl;
	}

	@Override
	public int findExpiredTaskCount(Map<String, Object> map) {
		return this.getPagableSqlSessionTemplate().selectOne(
				"findExpiredTaskCount", map);
	}

	@Override
	public PaginatedList<HomePageTaskRecord> findTasksByCdts(
			Map<String, Object> map, int start, int limit) {
		PreparedQuery<HomePageTaskRecord> pq = this
				.getPagableSqlSessionTemplate().findAll(
						FIND_TASKS_BY_CONDITIONS, map);
		PaginatedList<HomePageTaskRecord> pl = pq.list(new PaginateParams(
				new StartLimitPairImpl(start, limit)));
		return pl;
	}

	@Override
	public PaginatedList<HomePageTaskRecord> findTasksByState(
			Map<String, Object> map, int start, int limit) {
		PreparedQuery<HomePageTaskRecord> pq = this
				.getPagableSqlSessionTemplate()
				.findAll("findTasksByState", map);
		PaginatedList<HomePageTaskRecord> pl = pq.list(new PaginateParams(
				new StartLimitPairImpl(start, limit)));
		return pl;
	}

	public StatusDAO getStatusDAO() {
		return statusDAO;
	}

	public void setStatusDAO(StatusDAO statusDAO) {
		this.statusDAO = statusDAO;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Override
	public List<HomePageTaskRecord> getAllTasksWithAviator(
			Map<String, Object> params, AviatorExpression expression,
			Map<String, Object> aviatorParams, int limit) {
		AviatorResultHandler<HomePageTaskRecord> handler = new AviatorResultHandler<HomePageTaskRecord>(
				expression, aviatorParams, limit);
		this.getPagableSqlSessionTemplate().select(FIND_TASKS_BY_CONDITIONS, params,
				new RowBounds(0, Integer.MAX_VALUE), handler);
		return handler.getResultList();
	}
}
